package com.thanos.api.storage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * StorageController.java description：Thanos链存储RESTful API控制器
 *
 * @Author create on 2024-12-19
 */
@RestController
@RequestMapping("/api/storage")
@CrossOrigin(origins = "*")
public class StorageController {

    private static final Logger logger = LoggerFactory.getLogger(StorageController.class);

    @Autowired
    private StorageService storageService;

    /**
     * 获取服务状态和合约地址
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        try {
            String contractAddress = storageService.getContractAddress();
            Map<String, Object> response = new HashMap<>();
            response.put("status", "running");
            response.put("contractAddress", contractAddress);
            response.put("message", "Thanos storage service is running");
            response.put("service", "Thanos Chain Storage API");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("Error getting status: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("status", "error");
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 部署新合约
     */
    @PostMapping("/contract/deploy")
    public ResponseEntity<Map<String, Object>> deployContract() {
        try {
            Map<String, Object> result = storageService.deployContract();
            if ((Boolean) result.get("success")) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(500).body(result);
            }
        } catch (Exception e) {
            logger.error("Error deploying contract: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 设置键值对
     */
    @PostMapping("/set")
    public ResponseEntity<Map<String, Object>> setKeyValue(@RequestBody Map<String, String> request) {
        try {
            String key = request.get("key");
            String value = request.get("value");

            if (key == null || key.trim().isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("error", "Key cannot be null or empty");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            if (value == null) {
                value = "";
            }

            Map<String, Object> result = storageService.setKeyValue(key, value);
            if ((Boolean) result.get("success")) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(500).body(result);
            }
        } catch (Exception e) {
            logger.error("Error setting key-value: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取键对应的值
     */
    @GetMapping("/get/{key}")
    public ResponseEntity<Map<String, Object>> getKeyValue(@PathVariable String key) {
        try {
            if (key == null || key.trim().isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("error", "Key cannot be null or empty");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            Map<String, Object> result = storageService.getKeyValue(key);
            if ((Boolean) result.get("success")) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(500).body(result);
            }
        } catch (Exception e) {
            logger.error("Error getting value for key '{}': {}", key, e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 执行基础存储测试
     */
    @PostMapping("/test/basic")
    public ResponseEntity<Map<String, Object>> runBasicStorageTest() {
        try {
            Map<String, Object> result = storageService.runBasicStorageTest();
            if ((Boolean) result.get("success")) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(500).body(result);
            }
        } catch (Exception e) {
            logger.error("Error in basic storage test: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 执行多用户存储测试
     */
    @PostMapping("/test/multi-user")
    public ResponseEntity<Map<String, Object>> runMultiUserStorageTest() {
        try {
            Map<String, Object> result = storageService.runMultiUserStorageTest();
            if ((Boolean) result.get("success")) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(500).body(result);
            }
        } catch (Exception e) {
            logger.error("Error in multi-user storage test: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 执行所有测试用例
     */
    @PostMapping("/test/all")
    public ResponseEntity<Map<String, Object>> runAllTests() {
        try {
            Map<String, Object> basicTestResult = storageService.runBasicStorageTest();
            Map<String, Object> multiUserTestResult = storageService.runMultiUserStorageTest();

            boolean allSuccess = (Boolean) basicTestResult.get("success") &&
                               (Boolean) multiUserTestResult.get("success");

            Map<String, Object> result = new HashMap<>();
            result.put("success", allSuccess);
            result.put("message", "All storage tests completed");
            result.put("basicStorageTest", basicTestResult);
            result.put("multiUserStorageTest", multiUserTestResult);

            if (allSuccess) {
                return ResponseEntity.ok(result);
            } else {
                return ResponseEntity.status(500).body(result);
            }
        } catch (Exception e) {
            logger.error("Error running all tests: {}", e.getMessage(), e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
}
